package com.ysgsignin.wxinfo.controller;

import com.aliyun.facebody20191230.Client;
import com.aliyun.facebody20191230.models.CompareFaceRequest;
import com.aliyun.facebody20191230.models.CompareFaceResponse;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import com.ysgsignin.common.annotation.Log;
import com.ysgsignin.common.core.controller.BaseController;
import com.ysgsignin.common.core.domain.AjaxResult;
import com.ysgsignin.common.core.page.TableDataInfo;
import com.ysgsignin.common.enums.BusinessType;
import com.ysgsignin.common.utils.poi.ExcelUtil;
import com.ysgsignin.wxinfo.domain.WxStudntimages;
import com.ysgsignin.wxinfo.service.IWxStudntimagesService;
import com.ysgsignin.wxinfo.util.AliyunOSSUtil;
import com.ysgsignin.wxinfo.util.Sample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 学生--上传图片-人脸识别Controller
 *
 * @author ysg
 * @date 2023-09-13
 */
@RestController
@RequestMapping("/wxinfo/studntimages")
public class WxStudntimagesController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(WxStudntimagesController.class);
    private static final String TO_PATH = "upload";
    private static final String RETURN_PATH = "success";
    @Autowired
    private IWxStudntimagesService wxStudntimagesService;

    //    /**
//     * @param request
//     * @param response
//     * @param imageName 学生学号
//     * @return 本地上传
//     * @throws Exception
//     */
//    @RequestMapping("/picture")
//    public String uploadPicture(HttpServletRequest request, HttpServletResponse response,
//                                @RequestParam("imageName") @NotBlank String imageName) throws Exception {
//        WxStudntimages wxStudntimages=new WxStudntimages();
//        wxStudntimages.setImageName(imageName); //学号
//        String filePath = "";
//        request.setCharacterEncoding("utf-8"); //设置编码
//        //String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
//        String directory =simpleDateFormat.format(new Date());
//        //System.out.println(realPath);
//        File dir = new File(fileSavePath);
//        System.out.println(dir.getPath());
//        //文件目录不存在，就创建一个
//        if (!dir.isDirectory()) {
//            dir.mkdirs();
//        }
//        try {
//            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
//            //获取formdata的值
//            Iterator<String> iterator = req.getFileNames();
//            System.out.println(req);
//            while (iterator.hasNext()) {
//                MultipartFile file = req.getFile(iterator.next());
//                String fileName = file.getOriginalFilename();
//                //真正写到磁盘上
//                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//                String newFileName= UUID.randomUUID().toString().replaceAll("-", "")+suffix;
//                File file1 = new File(fileSavePath+"/" + newFileName);
//                file.transferTo(file1);
//                System.out.println(file1.getPath());
//                filePath = request.getScheme() + "://" +
//                        request.getServerName() + ":"
//                        + request.getServerPort()
//                        +"/upload/"+ newFileName;
//                wxStudntimages.setImageUrl(filePath); //学生路径地址
//                List<WxStudntimages> list = wxStudntimagesService.selectWxStudntimagesList(wxStudntimages);
//                System.out.println(list.size());
//                if (list.size()!=0){
//                    System.out.println(list);
//                //  学生更新上传图片
//                    Long imageId = list.get(0).getImageId();
//                    WxStudntimages wxStudntimagesUpdate=new WxStudntimages();
//                    wxStudntimagesUpdate.setImageId(imageId);
//                    wxStudntimagesUpdate.setImageUrl(filePath);
//                    wxStudntimagesService.updateWxStudntimages(wxStudntimagesUpdate);
//                }else {
//                    //  新增学生人脸识别图
//                    wxStudntimagesService.insertWxStudntimages(wxStudntimages);
//                    System.out.println("访问图片路径:" + filePath);
//                }
//            }
//        } catch (Exception e) {
//            logger.error("", e);
//        }
//        return filePath;
//    }
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
    @Value("${file-save-path}")
    private String fileSavePath;
    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;


    /**
     * 学生录入人脸图片
     */
    @CrossOrigin  //解决跨域
    @RequestMapping(value = "/ossuploadfile")
    public String uploadBlog(@RequestParam("file") MultipartFile file,
                             @RequestParam("imageName") String imageName) {
        String filename = file.getOriginalFilename();
        System.out.println(filename + "==filename");
        try {
            if (file != null) {
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    System.out.println("上传的oss路径：" + newFile);
                    // 上传到OSS
                    String uploadUrl = aliyunOSSUtil.upLoad(newFile, imageName);
//                    System.out.println("上传的oss路径："+uploadUrl);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return RETURN_PATH;
    }


    /**
     * 使用脸识别对比  结合OSS 阿里云存储进行人脸识别比较
     *
     * @param
     * @return
     */
    @PostMapping("/wxSample")
    public  AjaxResult  SampleWxImages(@RequestParam("file") MultipartFile file, @RequestParam("imageName") @NotBlank String imageName) throws Exception {
        WxStudntimages OneStudent = wxStudntimagesService.selectWxStudntByNameNoimagesList(imageName);
        if (OneStudent == null) {
            return AjaxResult.success("你还未人脸录入", 300);
        } else {
            String imageUrl = OneStudent.getImageUrl();//之前学生录入的学生的图片信息
            System.out.println("之前学生录入的图片" + imageUrl);
            String filename = file.getOriginalFilename();
            String uploadUrl = null;
            try {
                if (file != null) {
                    if (!"".equals(filename.trim())) {
                        File newFile = new File(filename);
                        FileOutputStream os = new FileOutputStream(newFile);
                        os.write(file.getBytes());
                        os.close();
                        file.transferTo(newFile);
                        // 当前人脸录入的图片上传到OSS
                        uploadUrl = aliyunOSSUtil.compareupLoad(newFile, imageName);
                        System.out.println("当前人脸录入的图片：" + uploadUrl);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            Client client = Sample.createClient("LTAI5tHsKJnX3jJ2eMMRC57P", "0EGKN3anHwi1FfnbGkCqnchVob6jjx");
            CompareFaceRequest compareFaceRequest = new CompareFaceRequest()
                    .setImageURLA(imageUrl)  // 之前学生录入的图片
                    .setImageURLB("https://studentimage.oss-cn-shanghai.aliyuncs.com/" + uploadUrl); //学生签到的图片
            RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            CompareFaceResponse resp = client.compareFaceWithOptions(compareFaceRequest, runtime);
            System.out.println(Common.toJSONString(resp.getBody().getData()));
            return success(Common.toJSONString(resp.getBody().getData()));
        }
    }

    /**
     * 微信接口----查询当前学生的图片人脸的数据
     */
    @GetMapping("/wxlist")
    public TableDataInfo wxlist(WxStudntimages wxStudntimages) {
        startPage();
        List<WxStudntimages> list = wxStudntimagesService.selectWxStudntimagesList(wxStudntimages);
        return getDataTable(list);
    }


    /**
     * 查询学生--上传图片-人脸识别列表
     */
    @PreAuthorize("@ss.hasPermi('wxinfo:studntimages:list')")
    @GetMapping("/list")
    public TableDataInfo list(WxStudntimages wxStudntimages) {
        startPage();
        List<WxStudntimages> list = wxStudntimagesService.selectWxStudntimagesList(wxStudntimages);
        return getDataTable(list);
    }


    /**
     * 导出学生--上传图片-人脸识别列表
     */
    @PreAuthorize("@ss.hasPermi('wxinfo:studntimages:export')")
    @Log(title = "学生--上传图片-人脸识别", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WxStudntimages wxStudntimages) {
        List<WxStudntimages> list = wxStudntimagesService.selectWxStudntimagesList(wxStudntimages);
        ExcelUtil<WxStudntimages> util = new ExcelUtil<WxStudntimages>(WxStudntimages.class);
        util.exportExcel(response, list, "学生--上传图片-人脸识别数据");
    }

    /**
     * 获取学生--上传图片-人脸识别详细信息
     */
    @PreAuthorize("@ss.hasPermi('wxinfo:studntimages:query')")
    @GetMapping(value = "/{imageId}")
    public AjaxResult getInfo(@PathVariable("imageId") Long imageId) {
        return success(wxStudntimagesService.selectWxStudntimagesByImageId(imageId));
    }

    /**
     * 新增学生--上传图片-人脸识别
     */
    @PreAuthorize("@ss.hasPermi('wxinfo:studntimages:add')")
    @Log(title = "学生--上传图片-人脸识别", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WxStudntimages wxStudntimages) {
        return toAjax(wxStudntimagesService.insertWxStudntimages(wxStudntimages));
    }

    /**
     * 修改学生--上传图片-人脸识别
     */
    @PreAuthorize("@ss.hasPermi('wxinfo:studntimages:edit')")
    @Log(title = "学生--上传图片-人脸识别", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WxStudntimages wxStudntimages) {
        return toAjax(wxStudntimagesService.updateWxStudntimages(wxStudntimages));
    }

    /**
     * 删除学生--上传图片-人脸识别
     */
    @PreAuthorize("@ss.hasPermi('wxinfo:studntimages:remove')")
    @Log(title = "学生--上传图片-人脸识别", businessType = BusinessType.DELETE)
    @DeleteMapping("/{imageIds}")
    public AjaxResult remove(@PathVariable Long[] imageIds) {
        return toAjax(wxStudntimagesService.deleteWxStudntimagesByImageIds(imageIds));
    }
}
